// 文件路径: src/main/java/csu/web/credit_bank/service/impl/PoetryChallengeServiceImpl.java
package csu.web.credit_bank.service.impl;

import csu.web.credit_bank.pojo.dto.DailyQuizStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import csu.web.credit_bank.pojo.dto.JinrishiciResponse;
import csu.web.credit_bank.pojo.dto.PoetryQuestionDTO;
import csu.web.credit_bank.service.CreditRecordsService;
import csu.web.credit_bank.service.CreditSummaryService;
import csu.web.credit_bank.service.PoetryChallengeService;
import csu.web.credit_bank.utils.Result;
import csu.web.credit_bank.utils.UUIDManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.*;

@Service
public class PoetryChallengeServiceImpl implements PoetryChallengeService {

    @Autowired
    private UUIDManager uuidManager;
    @Autowired
    private CreditRecordsService creditRecordsService;
    @Autowired
    private CreditSummaryService creditSummaryService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private CacheManager cacheManager;
    @Value("${poetry.api.token}")
    private String jinrishiciToken;

    private static final String JINRISHICI_API_URL = "https://v2.jinrishici.com/sentence";

    private static final int MAX_POETRY_QUESTIONS_PER_DAY = 5;
    private static final int POETRY_CREDITS_PER_CORRECT_ANSWER = 2;

    private DailyQuizStatus getOrCreateDailyStatus(String userId) {
        Cache cache = cacheManager.getCache("dailyQuizStatusCache");
        String cacheKey = userId + "_" + LocalDate.now().toString();
        DailyQuizStatus status = cache.get(cacheKey, DailyQuizStatus.class);
        if (status == null) {
            status = new DailyQuizStatus();
            cache.put(cacheKey, status);
        }
        return status;
    }

    @Override
    public Result<PoetryQuestionDTO> getPoetryChallenge(String userId) {
        DailyQuizStatus status = getOrCreateDailyStatus(userId);

        if (status.getPoetryAnsweredCount() >= MAX_POETRY_QUESTIONS_PER_DAY) {
            return Result.failure("您今日的古诗词挑战次数已达上限，请明天再来！");
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-User-Token", jinrishiciToken);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            ResponseEntity<JinrishiciResponse> responseEntity = restTemplate.exchange(
                    JINRISHICI_API_URL,
                    HttpMethod.GET,
                    entity,
                    JinrishiciResponse.class
            );

            JinrishiciResponse response = responseEntity.getBody();
            if (response == null || response.getData() == null || response.getData().getOrigin() == null) {
                return Result.failure("获取诗词失败，请稍后重试");
            }
            JinrishiciResponse.Origin origin = response.getData().getOrigin();
            String poemId = response.getData().getId();
            List<String> originalLines = origin.getContent();

            if (originalLines.size() < 2) {
                return getPoetryChallenge(userId);
            }

            List<PoetryQuestionDTO.Line> questionLines = new ArrayList<>();
            List<String> correctAnswers = new ArrayList<>();

            for (int i = 0; i < originalLines.size(); i++) {
                String lineContent = originalLines.get(i);
                PoetryQuestionDTO.Line line = new PoetryQuestionDTO.Line();
                if ((i + 1) % 2 == 0 && !lineContent.trim().isEmpty()) {
                    line.setType("input");
                    line.setPlaceholder("请填写");
                    correctAnswers.add(lineContent.replaceAll("[，。？！；]", ""));
                } else {
                    line.setType("text");
                    line.setContent(lineContent);
                }
                questionLines.add(line);
            }

            if (correctAnswers.isEmpty()) {
                return getPoetryChallenge(userId);
            }

            Cache cache = cacheManager.getCache("poetryAnswers");
            if (cache != null) {
                cache.put(poemId, correctAnswers);
            }

            PoetryQuestionDTO questionDTO = new PoetryQuestionDTO();
            questionDTO.setId(poemId);
            questionDTO.setTitle(origin.getTitle());
            questionDTO.setAuthor(origin.getAuthor());
            questionDTO.setDynasty(origin.getDynasty());
            questionDTO.setLines(questionLines);

            return Result.success(questionDTO);

        } catch (Exception e) {
            return Result.failure("生成题目时发生错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> processChallenge(String userId, String poemId, List<String> userAnswers) {
        if (userId == null || userId.isEmpty()) {
            return Result.failure("内部错误：用户ID无效");
        }
        Cache cache = cacheManager.getCache("poetryAnswers");
        List<String> correctAnswers = null;
        if (cache != null) {
            correctAnswers = cache.get(poemId, List.class);
        }

        if (correctAnswers == null) {
            return Result.failure("答案已过期或无效，请刷新题目重试");
        }
        if (userAnswers == null || userAnswers.size() != correctAnswers.size()) {
            return Result.failure("提交的答案数量不正确");
        }

        for (int i = 0; i < correctAnswers.size(); i++) {
            String userAnswer = userAnswers.get(i);
            String correctAnswer = correctAnswers.get(i);
            String formattedUserAnswer = (userAnswer != null) ? userAnswer.trim().replaceAll("[，。？！；]", "") : "";
            if (!correctAnswer.trim().equalsIgnoreCase(formattedUserAnswer)) {
                return Result.failure("答案有误，请重新尝试");
            }
        }
        if (cache != null) {
            cache.evict(poemId);
        }
        DailyQuizStatus status = getOrCreateDailyStatus(userId);
        if (status.getPoetryAnsweredCount() >= MAX_POETRY_QUESTIONS_PER_DAY) {
            return Result.failure("您今日的挑战次数已用完。");
        }

        status.setPoetryAnsweredCount(status.getPoetryAnsweredCount() + 1);
        String cacheKey = userId + "_" + LocalDate.now().toString();
        cacheManager.getCache("dailyQuizStatusCache").put(cacheKey, status);

        try {
            String message = String.format("回答正确！今日已完成 %d/5。",
                    POETRY_CREDITS_PER_CORRECT_ANSWER, status.getPoetryAnsweredCount());
            return Result.success(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发放学分失败，事务已回滚。", e);
        }
    }
}
